/**----------------------------------------
 * @description 任务管理类
 * @author      lxc
 * @file        TaskManager.ts
 * @Date        2022-05-22
 * @version     1.0.0
 * ----------------------------------------
 */

import { MsgComponent } from "../message/MsgComponent";
import { Task } from "./Task";
import { TaskState } from "./TaskDefine";
import { TaskEnum } from "./TaskEnum";

export class TaskManager extends MsgComponent{
    private taskList : Task[] = []

    private complateTasks = []

    registTask(taskName : TaskEnum, complateCallBack ?: Function){
        this.taskList.push(null);
    }

    dumpTasks(){
        this.taskList.forEach(task => {
            task.dumpTask()
        })
    }

    protected update(dt: number): void {
        this.complateTasks = []
        this.excuteTask(dt)
        this.removeComplateTask()
    }

    excuteTask(dt){
        this.taskList.forEach((task : Task) => {
            if(task.getState() == TaskState.Complate){
                this.complateTasks.push(task)
            }else if (task.getState() == TaskState.Wait){
                task.taskExcute(dt)
            }else{
                task.judgeTaskComplate(dt)
            }
        })
    }

    removeComplateTask(){
        if(this.complateTasks.length > 0){
            if(this.taskList.length > 0){
                this.complateTasks.forEach((task)=>{
                    let index = this.taskList.indexOf(task)
                    if (index > 0){
                        this.taskList.splice(index,1)
                    }
                })
            }else{
                this.printError("task length is null")
            }
        }
    }
}